package pl.edu.agh.mwo.ui.app;

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;

import pl.edu.agh.mwo.model.MenadzerPracownikow;
import pl.edu.agh.mwo.ui.action.AboutAction;
import pl.edu.agh.mwo.ui.action.EksportAction;
import pl.edu.agh.mwo.ui.action.ImportAction;
import pl.edu.agh.mwo.ui.chart.SampleChartsFactory;
import pl.edu.agh.mwo.ui.chart.WykresSlupkowy;

public class MainApp {

	private final AboutAction aboutAction = new AboutAction();
	private MenadzerPracownikow mp;
	private JFrame frame;
	private JTable table;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			System.out.println("Error setting native LAF: " + e);
		}
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainApp window = new MainApp();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public MainApp() {
		mp = new MenadzerPracownikow();
		initialize(mp);

	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize(final MenadzerPracownikow mp) {
		frame = new JFrame();
		frame.setBounds(100, 100, 650, 485);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JMenuBar menuBar = new JMenuBar();
		frame.setJMenuBar(menuBar);

		JMenu mnFile = new JMenu("Plik");
		menuBar.add(mnFile);

		JMenuItem mntmImportujDane = new JMenuItem("Importuj dane");
		mntmImportujDane.setAction(new ImportAction(frame, mp, this));
		mnFile.add(mntmImportujDane);

		JMenuItem mntmZapiszDoCsv = new JMenuItem("Zapisz do csv");
		mntmZapiszDoCsv.setAction(new EksportAction(this, mp));
		mnFile.add(mntmZapiszDoCsv);

		JMenu mnPomoc = new JMenu("Pomoc");
		menuBar.add(mnPomoc);

		JMenuItem mntmOProgramie = new JMenuItem("O programie");
		mntmOProgramie.setAction(aboutAction);
		mnPomoc.add(mntmOProgramie);

		JPanel panel = new JPanel();

		final ChartPanel panel_1 = new ChartPanel(
				SampleChartsFactory.createPieChart(mp, -1));

		final ChartPanel panel_2 = new ChartPanel(
				WykresSlupkowy.createBoxChart(mp, -1));

		JButton btnZapiszJako = new JButton("Zapisz jako");

		btnZapiszJako.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					JFreeChart wykres = panel_1.getChart();
					zapiszWykresDoPliku(wykres);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		JButton btnZapiszJako_1 = new JButton("Zapisz jako");

		btnZapiszJako_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					JFreeChart wykres = panel_2.getChart();
					zapiszWykresDoPliku(wykres);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
		groupLayout
				.setHorizontalGroup(groupLayout
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								groupLayout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												groupLayout
														.createParallelGroup(
																Alignment.TRAILING)
														.addComponent(
																btnZapiszJako_1)
														.addGroup(
																Alignment.LEADING,
																groupLayout
																		.createSequentialGroup()
																		.addComponent(
																				panel,
																				GroupLayout.PREFERRED_SIZE,
																				200,
																				GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				ComponentPlacement.UNRELATED)
																		.addGroup(
																				groupLayout
																						.createParallelGroup(
																								Alignment.LEADING)
																						.addComponent(
																								panel_2,
																								GroupLayout.DEFAULT_SIZE,
																								GroupLayout.DEFAULT_SIZE,
																								Short.MAX_VALUE)
																						.addGroup(
																								groupLayout
																										.createParallelGroup(
																												Alignment.TRAILING,
																												false)
																										.addComponent(
																												panel_1,
																												Alignment.LEADING,
																												GroupLayout.DEFAULT_SIZE,
																												400,
																												Short.MAX_VALUE)
																										.addComponent(
																												btnZapiszJako)))))
										.addContainerGap(22, Short.MAX_VALUE)));
		groupLayout
				.setVerticalGroup(groupLayout
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								groupLayout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												groupLayout
														.createParallelGroup(
																Alignment.LEADING)
														.addGroup(
																groupLayout
																		.createSequentialGroup()
																		.addComponent(
																				panel_1,
																				GroupLayout.PREFERRED_SIZE,
																				170,
																				GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				ComponentPlacement.RELATED)
																		.addComponent(
																				btnZapiszJako)
																		.addPreferredGap(
																				ComponentPlacement.UNRELATED)
																		.addComponent(
																				panel_2,
																				GroupLayout.PREFERRED_SIZE,
																				160,
																				GroupLayout.PREFERRED_SIZE))
														.addComponent(
																panel,
																GroupLayout.PREFERRED_SIZE,
																370,
																GroupLayout.PREFERRED_SIZE))
										.addPreferredGap(
												ComponentPlacement.RELATED)
										.addComponent(btnZapiszJako_1)
										.addGap(20)));
		panel.setLayout(new GridLayout(1, 0, 0, 0));
		// tabela
		String[] columnNames = { "Imie", "Nazwisko", "Czas pracy" };

		table = new JTable(createTableFromModel(), columnNames);
		table.setModel(new DefaultTableModel());
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.getSelectionModel().addListSelectionListener(
				new ListSelectionListener() {

					@Override
					public void valueChanged(ListSelectionEvent e) {
						if (panel_1 == null || panel_2 == null) {
							return;
						}
						if (e.getValueIsAdjusting() == false) {
							panel_1.setChart(SampleChartsFactory
									.createPieChart(mp, table.getSelectedRow()));
							panel_2.setChart(WykresSlupkowy.createBoxChart(mp,
									table.getSelectedRow()));
						}
					}

				});

		JScrollPane scrollPane = new JScrollPane(table);
		panel.add(scrollPane);

		frame.getContentPane().setLayout(groupLayout);
	}

	public void updateTable() {
		String[] columnNames = { "Imie", "Nazwisko", "Czas pracy" };
		Object[][] data = createTableFromModel();
		DefaultTableModel model = (DefaultTableModel) table.getModel();
		// TODO
		model.setDataVector(data, columnNames);

		model.fireTableDataChanged();

	}

	private Object[][] createTableFromModel() {
		Object[][] data = new Object[mp.getListaPracownikow().size()][3];

		for (int i = 0; i < mp.getListaPracownikow().size(); i++) {
			data[i][0] = mp.getListaPracownikow().get(i).getImie();
			data[i][1] = mp.getListaPracownikow().get(i).getNazwisko();
			data[i][2] = mp.getListaPracownikow().get(i).getZbiorczyCzasPracy();
		}
		return data;
	}

	public void zapiszWykresDoPliku(JFreeChart wykres) throws IOException {
		JFileChooser chooser = new JFileChooser();
		String sciezka = "";
		// chooser.gets
		int rVal = chooser.showSaveDialog(frame);

		// int rVal = c.showSaveDialog(FileChooserTest.this);
		if (rVal == JFileChooser.APPROVE_OPTION) {
			sciezka = chooser.getSelectedFile().getAbsolutePath();

			File plik = new File(sciezka);
			ChartUtilities.saveChartAsJPEG(plik, wykres, 900, 900);
			JOptionPane.showMessageDialog(null, "Wykres zapisany w pliku "
					+ sciezka);
		}
	}

	public JFrame getFrame() {
		return frame;
	}

	public JTable getTable() {
		return table;
	}
	
	

}
